package com.front.web.wx;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bootdo.lvyou.domain.XcxConfig;
import com.bootdo.lvyou.service.LvyouMemberService;
import com.bootdo.lvyou.service.XcxConfigService;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.wx.domain.Config;
import com.bootdo.wx.service.ConfigService;
import com.bootdo.wx.service.WxUserService;
import com.front.web.wx.model.WechatTextMsg;
import com.front.web.wx.utils.MessageUtils;
import com.front.web.wx.utils.MobanMessageUtils;
import com.front.web.wx.utils.TokenUtils;
import com.front.web.wx.utils.WechatUtil;

@Controller
@RequestMapping("/f/")
public class WxFrontController extends BaseController{
	@Autowired
	private ConfigService configService;
	@Autowired
	private WxUserService userService;
	@Autowired
	private MessageUtils messageUtils;
	@Autowired
	private XcxConfigService xcxConfigService;
	@Autowired
	private LvyouMemberService lvyouMemberService;

	/**微信域名验证
	 * http://gmvyax.natappfree.cc/f/wxcallback?userId=?
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("wxcallback")
	public  void wxcallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
	        //获取Get请求携带参数
	        String content=request.getQueryString();
	        System.out.println(content);
	        Long userId = StringUtils.isEmpty(request.getParameter("userId"))?0:Long.parseLong(request.getParameter("userId"));	  
	        Config c   =   configService.getByUserId(userId);	    
            //检查消息是否来自微信服务器
            String echostr=WechatUtil.CheckSignature(request,c.getToken());
            System.out.println("echostr -> "+echostr);   
            //返回echostr给微信服务器  
            OutputStream os= response.getOutputStream();
            if(!StringUtils.isEmpty(echostr)) {
            	 os.write(URLEncoder.encode(echostr,"UTF-8").getBytes());
                 os.flush();
                 os.close();
                 return ;
            }     
            
            InputStream in = request.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            String str = "";
            while((len = in.read(b)) != -1) {
            	str += new String(b,0,len);      	
            }
            in.close();
            System.err.println("请求->"+str);
            String r = messageUtils.dealWechatMsg(str);
            System.err.println("返回->"+r);
            if(StringUtils.isEmpty(r)) {
            	r = "";            
            }
            os.write(r.getBytes());
            os.flush();
            os.close();
    }
	
	

    /**
     * 处理文本消息
     * @return
     */
    private String dealTextMsg(Element rootElement)
    {

        WechatTextMsg tWechatTextMsg = new WechatTextMsg();
        // 依次赋值
        tWechatTextMsg.setCreateTime(rootElement.elementText("CreateTime"));
        tWechatTextMsg.setFromUserName(rootElement.elementText("FromUserName"));
        tWechatTextMsg.setToUserName(rootElement.elementText("ToUserName"));
        tWechatTextMsg.setMsgType(rootElement.elementText("MsgType"));
        tWechatTextMsg.setMsgId(rootElement.elementText("MsgId"));
        tWechatTextMsg.setContent(rootElement.elementText("Content"));
        System.out.println("传入的消息是：" + tWechatTextMsg.getContent());
        // 后续可处理保存到数据库及数据分析等，现在直接返回结果
        // 将数据转存至数据库
        // Connection conn = DBConnPool.getConnection();
        return "传入的文本消息处理完毕";
    }
	
	
	

	/* 测试token
	 * http://gmvyax.natappfree.cc/f/test?userId=1
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("test")
	public  String test(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam("userId") Long userId) throws IOException {
		String openId = request.getParameter("openId");
		Config config  = configService.getByUserId(userId);
		if(StringUtils.isEmpty(openId)) {
			String r = WechatUtil.getCode(request, config, "/f/test?userId="+config.getUserId());
			return "redirect:"+r;
		}	
		System.err.println("openId = "+openId);
		return "blue/time";
    }
	
	
	/* 测试token
	 * http://k9fzmw.natappfree.cc/f/testApi?userId=1
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("testApi")
	public  String testApi(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam("userId") Long userId) throws Exception {		
		Config config  = configService.getByUserId(userId);

		Map<String, String> result = new HashMap<String, String>();
		result = WechatUtil.getJsApi(config, request);
		request.setAttribute("signature", result.get("signature"));
		request.setAttribute("nonceStr", result.get("nonceStr"));
		request.setAttribute("timestamp", result.get("timestamp"));
		request.setAttribute("weChatAppId",config.getWxAppId());
		return "blue/time";
    }
	
	
	
	
	/* 测试token
	 * http://k9fzmw.natappfree.cc/f/testMoban?userId=1
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("testMoban")
	public  String testMoban(HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam("userId") Long userId) throws Exception {		
		Config config  = configService.getByUserId(userId);
		MobanMessageUtils.sendWxMobanXaoxi(config, "oG6OxxHiqM6jyLMrAU865iJuDiiY", "cBMOskJHqi479Gs7hiR_ZzoRHicMgjL-DVNfL91uPg0",
				"firstData", "keyword1", "keyword2", "keyword3", "keyword4", "remark", "http://www.baidu.com");
		
		return "blue/time";
    }
	
	
	
	
	/**
	 * http://gmvyax.natappfree.cc/f/getWxCode
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("getWxCode")
	public String getWxCode(HttpServletRequest request, 
			HttpServletResponse response) throws UnsupportedEncodingException {
		String code =  request.getParameter("code");
		String state = request.getParameter("state");
		String userId = request.getParameter("userId");
		System.out.println("code = "+ code + "state = "+ state);
		Config config = configService.getByUserId(Long.parseLong(userId));		
	    String openId = WechatUtil.getOpenId(code, config, userService);	
	   return "redirect:"+state+"&openId="+openId;
	}

	/**
	 *  http://pi2ufx.natappfree.cc/f/getWxCode
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("getLvyouWxCode")
	public String getLvyouWxCode(HttpServletRequest request,
							HttpServletResponse response) throws UnsupportedEncodingException {
		String code =  request.getParameter("code");
		String state = request.getParameter("state");
		System.out.println("code = "+ code + "state = "+ state);
		XcxConfig xcxConfig = xcxConfigService.list(new HashMap<>()).get(0);
		String openId = WechatUtil.getlvyouOpenId(code, xcxConfig, lvyouMemberService);
		return "redirect:"+state+"&openId="+openId;
	}
	
	
	
}

